package middlewares

import (
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/x/errors"
	xhttp "github.com/zeromicro/x/http"
	"microdemo/restful/bff/internal/types"
	"net/http"
)

type GlobalMiddleware struct {
}

func NewGlobalMiddleware() *GlobalMiddleware {
	return &GlobalMiddleware{}
}

func (m *GlobalMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		logx.Info("全局中间件前面的执行")
		// panic 异常一旦引发就会导致程序崩溃。Go 语言为开发者提供了专用于拦截运行时 panic 的内建函数 recover()
		defer func() {
			if r := recover(); r != any(nil) {
				//打印错误堆栈信息
				logx.Error("运行时引发 panic，原因为: %s", errorToString(r))
				// 此处可以异步调用钉钉通知等
				//封装通用 json 返回
				xhttp.JsonBaseResponseCtx(request.Context(), writer, errors.New(types.Server_Error.Code, types.Server_Error.Msg))
			}
		}()
		next(writer, request)
		header := writer.Header()
		logx.Info(header)
		logx.Info("全局中间件后面的执行")
	}
}

// recover 错误转 string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}
